<template>
  <section>
    <!--订单基础信息-->
    <el-form label-width="90px" size="mini">
      <el-form-item label="订单标题：">
        <el-input v-model="orderForm.title" style="width: 20%" size="mini"></el-input>
      </el-form-item>
      <el-form-item label="选择用户：">
        <el-select v-model="selCustomer"  :filterable="true" clearable  remote :reserve-keyword="false" size="mini" allow-create
                   default-first-option  placeholder="请输入姓名" :remote-method="remoteMethod" value-key="id">
          <el-option v-for="(customer,index) in customerList" :key="index" :label="customer.name" :value="customer" v-if="customerList">
            <span style="float: left">{{ customer.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ customer.phone }}</span>
          </el-option>
        </el-select>
        <el-select v-model="selMember" value-key="id" v-if="memberList && memberList.length>0" size="mini">
          <el-option v-for="(member,index) in memberList" :key="index" :label="member.userName" :value="member" >
            <span style="float: left">{{ member.userName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ member.phone }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择商品：">
        <el-select v-model="selGoods" placeholder="商品" size="mini" value-key="id">
          <el-option v-for="goods in mallGoodsList" :key="goods.id" :label="goods.title" :value="goods"/>
          <el-pagination v-show="totalPage>0" layout="prev, pager, next" :page-count="totalPage" @current-change="goPage"/>
        </el-select>
      </el-form-item>
      <el-form-item label="商品Sku："  v-if="selGoods">
        <el-select v-model="selGoodsSku" placeholder="商品规格" size="mini"  @visible-change="selSkuBtn" value-key="id">
          <el-option v-for="goodsSku in selGoods.goodsSkus" :key="goodsSku.id" :label="goodsSku.props" :value="goodsSku"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单优惠：" v-if="selGoods">
        <el-input size="mini" v-model="orderForm.salePrice" style="width:200px"/>
      </el-form-item>
      <el-form-item label="地址："  v-if="orderAddress">
        在这里选地址
      </el-form-item>
    </el-form>
    <!--优惠券区-->
    <!--地址栏-->
    <!--订单项-->
    <el-row>
      <el-table :data="orderItemsForm" show-summary  :summary-method="getSummary">
        <el-table-column type="index"></el-table-column>
        <el-table-column label="规格" prop="title"  width="130"/>
        <el-table-column label="单价" prop="price" width="80"/>
        <el-table-column label="编码" prop="sn" width="150"/>
        <el-table-column label="数量" width="150">
          <template slot-scope="scope">
            <el-row class="numBox">
              <el-col :span="3"  >
                <i  class="el-icon-plus" size="mini" @click='increase(scope.row)' ></i>
              </el-col>
              <el-col :span="3" class="num" style="text-align: center">
                {{scope.row.num}}
              </el-col>
              <el-col :span="3"   >
                <i class="el-icon-minus" size="mini" @click='decrease(scope.row)'></i>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="价格" prop="totalPrice">
          <template slot-scope="scope">
            ¥{{(scope.row.price*scope.row.num).toFixed(2)}}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-row v-if="scope.row.data.props.needCustomerId && customerInMemberList && customerInMemberList.length>0">
              <el-row v-for="(customerId,index) in scope.row.data.customerIds" :key="customerId.id">
                <el-select v-model="scope.row.data.customerIds[index]" value-key="id" size="mini">
                  <el-option v-for="(customer,index) in customerInMemberList" :key="index" :label="customer.name" :value="customer.id">
                    <span style="float: left">{{ customer.name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ customer.phone }}</span>
                  </el-option>
                </el-select>
              </el-row>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row style="float: right;margin-top: 10px" v-if="orderItemsForm.length>0">
      <el-form label-width="100px" size="mini">
        <el-form-item label="订单金额：">{{getSum()}}</el-form-item>
        <el-form-item label="优惠金额：">{{orderForm.salePrice}}</el-form-item>
        <el-form-item label="实付金额：">{{getOrderPrices()}}</el-form-item>
        <el-form-item label="">
          <el-button size="mini" type="primary" @click="subOrderBtn">提交订单</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-dialog title="支付确定页" :visible.sync="showPayDialog">
      <show-pay :orders="checkOrders" :pay="currOrder" v-on:cancel="cancelShowPay"></show-pay>
    </el-dialog>
  </section>
</template>

<script>
  import showPay from '../showPay'
  import { mapActions,mapGetters} from 'vuex'
  import DateFormat from '@/common/date-formater'
  import errHandler from '@/assets/errHandler.js'
  import Vue from 'vue'//后续添加属性，需要vue联动
  export default {
    name: "mallOrders",
    components:{showPay},
    data() {
      return {
        orderForm:{
          title:'',
          salePrice:0,
          data:'{"userName":"张三","nationalCode":"510000","telNumber":"020-81167888","postalCode":"510000","provinceName":"广东省","cityName":"广州市","countyName":"海珠区","detailInfo":"新港中路397号"}'
        },
        mallGoodsList:null,
        selGoods:null,
        totalPage:0,
        customerList:null,
        selCustomer:null,
        memberList:null,
        selMember:null,
        orderItemsForm:[],
        goodsSkuList:null,
        selGoodsSku:null,
        orderAddress:false,
        customerInMemberList:null,
        showPayDialog:false,
        checkOrders:[],
        currOrder:null
      }
    },
    created(){
      console.log("___________？？？？")
      this.getMallGoodsList()
    },
    computed: {
      ...mapGetters(['department']),
    },
    watch:{
      orderItemsForm(nv,ov){
        nv.forEach(i=>{
          if(i.data.needAddress){
            this.orderAddress=true
            return
          }
        })
      },
      selCustomer(nv,ov){
        console.log('——————选择的customer——————————',typeof(nv))
        if(nv){
          this.selMember=null
          this.memberList=null
          if(typeof(nv) === "string"){
            //跳出新建用户的对话框
            this.$message('未找到该用户，请确认用户是否存在！')
          }else this.getMembersByCustomer(nv.name)
        }
      },
      selMember(nv,ov){
        // console.log('——————选择的member——————————',nv)
        if(nv){
          if(nv.customers.length<=0){
            this.$message('该账户下还未绑定用户，请确认！')
            return
          }
          this.customerInMemberList=nv.customers
          //获取账户下的优惠券
        }
      },
      selGoods(nv,ov){
        // console.log('——————选择的商品——————————',nv)
        nv.goodsSkus.forEach(s=>{
          console.log('看一看顺序1————————————————1111')
          s.data=nv.goodsType.data
          Vue.set(s.data,'customerIds',[''])
        })
        console.log('看一看顺序1————————————————222',this.selGoods)
        // console.log(this.selGoods)
      },
      selGoodsSku(nv,ov){
        console.log('——————选择的规格——————————',nv)
        console.log('看下当前商品-----',this.selGoods)
        let orderItems = this.orderItemsForm
        if(nv){
          let index = orderItems.findIndex(i => i.sn === nv.sn)
          if(index >= 0){//存在这个sku，那就数量+1
            this.increase(orderItems[index])
          }else {//不存在，就增加这个sku
            let item={
              title:this.selGoods.title,
              props:nv.props,
              sn:nv.sn,
              edit:false,
              num:1,
              data:nv.data,
              price:nv.price,
              sale:nv.sale
            }
            orderItems.push(item)
          }

          return
          let sku = nv
          sku.title = this.selGoods.title
          if(orderItems && orderItems.length >0){//如果当前订单规格存在并且有内容，就找一找选中的规格在订单规格内有没有
            let index = orderItems.findIndex(i => i.sn === sku.sn)
            if(index >= 0){//存在这个sku，那就数量+1
              this.increase(orderItems[index])
            }else {//不存在，就增加这个sku
              let tmp = {...sku,edit:false,num:1}
              orderItems.push(tmp)
            }
          }else {//如果当前订单规格不存在或者没有内容，就直接增加sku
            //不存在，就增加这个sku
            let tmp = {...sku,edit:false,num:1}
            orderItems.push(tmp)
          }
        }
      }
    },
    methods: {
      ...mapActions({
        fetch: 'fetch'
      }),
      getSum(){
        let sums = this.orderItemsForm.reduce((prev, curr) => {
          const value = Number(curr.totalPrice)
          if (!isNaN(value)) {
            return prev + curr.totalPrice
          } else {
            return prev
          }
        }, 0)
         sums=sums.toFixed(2)
        return sums
      },
      test(){
        console.log(this.orderItemsForm)
      },
      getMembersByCustomer(keywords){
        this.fetch({name:"getMembersByCustomer",data:{keywords}})
          .then(res=>{
            console.log('没有绑定？？？',res)
            if(res.length<=0){
              this.$message('该用户还未绑定账户，请确认！')
              return
            }
            this.memberList=res
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      selSkuBtn(e){
        if(e === true){
          this.selGoodsSku = null
        }
      },
      goPage(val){
        this.getMallGoodsList(val-1)
      },
      getMallGoodsList(pageNo){
        this.fetch({name:"getMallGoodsList",data:{page:pageNo?pageNo:0,storeId:this.department.id,size:5}})
          .then(res=>{
            console.log('商城商品—————列表—————————',res)
            this.mallGoodsList=res.content
            this.totalPage=res.totalPages
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
        // getMallGoodsList
      },
      remoteMethod(keywords) {
        clearTimeout()
        setTimeout(()=>{
          this.fetch({name:"getUserList",data:{keywords}})
            .then(res=>{
              // console.log(res)
              this.customerList=res.content
            })
            .catch(err=>{
              console.log(err)
              errHandler.handle(this,err)
            })},500)
      },
      makeOrderItems(order,items){
        console.log('看下要准备的数据----------',items)
        order.orderItems=[]
        for(let i=0;i<items.length;i++){
          let tmp = items[i]
          let detail = this.exchangeTitle(tmp.props)
          let o = {
            title:tmp.props,
            price:tmp.price,
            num:tmp.num,
            sn:tmp.sn,
            data:{...tmp.data,...detail}
          }
          order.orderItems.push(o)
        }
        console.log('看下------',order.orderItems)
        return JSON.stringify(order.orderItems)
      },
      exchangeTitle(title){
        let tmp={}
        let titles=title.split(';')
        titles.forEach(t=>{
          let kv = t.split(':')
          let k=kv[0]
          let v=kv[1]
          tmp[k]=v
        })
        // console.log(tmp)
        return tmp
      },
      preOrderMall(data){
        this.fetch({name:"preOrderMall",data})
          .then(res=>{
            console.log(res)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      createOrderByManager(data){
        console.log('管理员创建订单——————————————————————————',data)
        this.fetch({name:"createOrderByManager",data:data})
          .then(res=>{
            console.log('创建订单byAdmin——————————',res)
            this.$message('提交成功')
            this.currOrder=res
            this.checkOrders.push(res)
            this.showPayDialog=true
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      subOrderBtn(){
        //memberId、title、departmentId/departmentCode、data(选)、orderItems(选)、orderDiscounts(选)
        // console.log(this.selMember)
        this.orderForm.memberId=this.selMember.id
        let orderData = this.makeOrderItems(this.orderForm,this.orderItemsForm)
        this.orderForm.orderItems=orderData
        this.orderForm.departmentId=this.department.id
        console.log(this.orderForm)
        // this.createOrderByManager(this.orderForm)
      },
      increase(row){//增加数量
        console.log('————————————————',row)
        row.num +=1
        // row.totalPrice +=row.price
        row.data.customerIds.push('')
      },
      decrease(row){//减少数量
        row.num -=1
        // row.totalPrice -=row.price
        row.data.customerIds.splice(row.data.customerIds.length-1,1)
        if(row.num === 0){
          let index = this.orderItemsForm.findIndex(o => o.id === row.id )
          if(index >=0){
            this.orderItemsForm.splice(index,1)
          }
        }
      },
      getOrderPrices(){
        let sums=this.getSum()
        console.log(sums)
        console.log(this.orderForm.salePrice)
        let tmp=sums-this.orderForm.salePrice
        tmp = tmp.toFixed(2)
        console.log('实付----',tmp)
        return tmp
      },
      getSummary(param){
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          if(index === 5){
            const values = data.map(item => Number(item[column.property]))
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ' 元';
          }else {
            sums[index]=''
          }
        })
        return sums
      },
      cancelShowPay(){
        this.showPayDialog=false
      }
    }
  }
</script>

<style scoped>

</style>
